package com.tjh.gulimall.cart.interceptor;

import com.tjh.common.constant.AuthServerConstant;
import com.tjh.common.constant.CartConstant;
import com.tjh.common.vo.MemberRespVo;
import com.tjh.gulimall.cart.vo.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * day104：在目标方法执行之前，判断用户的登录状态，并封装传递给controller目标请求
 * Create by koala on 2021-05-16
 */
public class CartInterceptor implements HandlerInterceptor {

    //ThreadLocal可以实现同一个线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //登录
            userInfoTo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies){
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //如果没有临时用户分配一个临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uid);
        }
        //目标方法执行之前
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后,分配临时用户，让浏览器保存
     * 测试：
     *      1、浏览器访问 http://cart.gulimall.com/cart.html
     *      2、在浏览器中 --》f12 --》Application --》 Cookies 中找到name为user-key的cookie 说明成功的把临时用户保存下来
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //如果没有临时用户，保存一个临时用户
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

    }
}